<template>
  <div class="container">
    <el-card>
      <div slot="header">
        <span style="font-weight: 700; font-size: 22px">更换头像</span>
      </div>
      <ImageUpload ref="image" />
      <el-button
        icon="el-icon-upload2"
        type="primary"
        style="width: 150px; font-size: 12px; margin-top: 10px"
        @click="uploadImage"
        >上传图片</el-button
      >
    </el-card>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { updateAvatar } from '@/api/user'
import { Message } from 'element-ui'
export default {
  name: 'baseInfo',
  components: {
    ImageUpload
  },
  methods: {
    async uploadImage () {
      const file = await this.$refs.image.file
      console.log(file)
      // 图片转为base64的格式
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = async () => {
        console.log('file 转 base64结果：' + reader.result)
        await updateAvatar({ avatar: reader.result })
        Message.success('头像更新成功')
      }
      reader.onerror = function (error) {
        console.log('Error: ', error)
        Message.error('图片格式转换失败')
      }
      location.reload()
    }
  }
}
</script>

<style>
</style>
